import {AxiosRequestConfig, AxiosInstance, AxiosPromise} from "axios";
import URI from 'urijs'
import Axios from 'axios'
import {Message, MessageBox} from "element-ui";
import {Local} from "@/plugins/local";
import {Session} from "inspector";


const network: AxiosInstance = newNetwork();

function newNetwork() {
    return Axios.create({
        baseURL:"/api/v2/admin/"
    })
}

interface Meta{
    query?:any;
    data?:any;
}

export class NetworkError {

    constructor(code: number, message: string) {
    }
}

function NewNetWorkError(code: number, message: string) {
    Message({
        message: `[${code}]${message}`,
        type:"error",
        duration: 1000 * 2,
    });

    return new NetworkError(code,message)
}

interface NetworkResponse<T> {
    code: number
    message: string
    data:T
}

function Invoke<T = any>( opts: AxiosRequestConfig) : Promise<T>{

    if(Local.HasSession()) {

        let s = Local.GetSession();

        if(s === null) {
            s = {
                uid:"",
                token:""
            }
        }

        opts.params = Object.assign({},opts.params, {
            _uid: s.uid,
            _token: s.token,

        });
    }



    return new Promise<T>((resolve, reject) => {
        network.request(opts)
            .then(value => {

                if(value.status != 200) {
                     return reject(NewNetWorkError(value.status,value.statusText))
                }

                if (!value.data) {
                    return reject(NewNetWorkError(100,"返回空数据."))
                }

                let data = value.data;

                if(data.code === undefined) {
                    return reject(NewNetWorkError(101,"返回Code为空."))
                }

                if(data.code != 0 ){


                    if(data.code === 3) {
                        MessageBox.alert('您的登录已过期，或在其他地方登录系统', '登录已过期', {
                            confirmButtonText: '确定',
                            callback: action => {
                                Local.DeleteSession();
                                window.location.href = "/"
                            }
                        });
                    }

                    return reject(NewNetWorkError(data.code,data.message))
                }

                return resolve(data.data);
            }).catch(reject)
    })
}


export function POST<T= any>(url:string,data?: object,meta?: Meta) : Promise<T>{

    let m: Meta = meta?meta:{};
    let d: any = data?data:{};

    return Invoke<T>(
        {
            url:url,
            method:"post",
            params:m.query,
            headers: {
                "Content-Type": "application/json"
            },
            transformRequest: function (data: any) {
                return JSON.stringify(data)
            },
            data:d,
        },
    )
}

export function GET<T = any>(url: string, meta?: Meta): Promise<T>{

    let m: Meta = meta?meta:{};

    return Invoke({
        url:url,
        method:"get",
        params:m.query,
    })
}

export function DELETE<T=any>(url:string,meta?:Meta): Promise<T> {

    let m: Meta = meta?meta:{};

    return Invoke<T>(
        {
            url:url,
            method:"delete",
            params:m.query,
        }
    )
}
